
package com.dmyang.websocket;

import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;

import javax.servlet.http.HttpSession;
import java.util.Map;


/**
 * Socket建立连接（握手）和断开
 * 本类的作用：
 * 在连接成功前和成功后增加一些额外的功能
 */
public class HandShake implements HandshakeInterceptor {

	public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Map<String, Object> attributes) throws Exception {
		System.out.println("Websocket:用户[ID:" + ((ServletServerHttpRequest) request).getServletRequest().getSession(false).getAttribute("pk") + "]已经建立连接");
		if (request instanceof ServletServerHttpRequest) {
			ServletServerHttpRequest servletRequest = (ServletServerHttpRequest) request;
			HttpSession session = servletRequest.getServletRequest().getSession(false);
			// 标记用户
			String pk = (String) session.getAttribute("pk");
			String name = (String) session.getAttribute("name");
			String role = (String) session.getAttribute("role");//角色：医生或病人
			if(pk!=null){
//				这里添加的属性，将保存在socketSession的attribute中。
				attributes.put("pk", pk);
				attributes.put("name",name);
				attributes.put("role",role);
				if (role.equals("doctor")){
					attributes.put("treatNum",0);
					attributes.put("isBusy",false);
				}else if (role.equals("patient")){
					attributes.put("isTreated",false);
				}
			}else{
				return false;
			}
		}
		return true;
	}

	public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Exception exception) {
	System.out.println("after hand");
	
	}

}
